<?php

namespace app\company\controller;

use app\company\model\StoreSalesman;
use app\company\validate\StoreUserValidate;
use app\service\traits\Crud;
use app\company\model\StoreUser as StoreUserModel;
use app\company\model\Store;
use think\Response;

class StoreUser extends Base
{
    private StoreUserModel $model;

    use Crud;

    public function initialize()
    {
        parent::initialize();
        $this->model            = new StoreUserModel();
        $this->validateClass    = StoreUserValidate::class;
        $this->withSearch       = 'id,real_name,mobile,is_salesman';
        $this->isGs             = true;
        $this->checkUniqueField = ['mobile', "user_name"];
    }

    public function format($list): mixed
    {
        return $list->each(function ($item) {
//            $store_names       = Store::where('salesman_id', $item->id)->column('name');
//            $item->store_names = implode(',', $store_names);
            $storeIds = StoreSalesman::where('store_user_id', $item->id)->column('store_id');
            $store_names = Store::whereIn('id', $storeIds)->column('name');
            $item->store_names = implode(',', $store_names);
            $item->money       = $item->storeUserAccountO()->value('money');
            $item->supplier_name = $item->supplier_id ? \app\company\model\Supplier::where('id', $item->supplier_id)->value('name') : '';
        });
    }

    /**
     * 下载模板
     * @return Response
     */
    public function downloadTemplate(): Response
    {
        $storeUserId = request()->param('store_user_id',0);
        $model = new store();
        if($storeUserId){
            $bindStoreIds = StoreSalesman::where('store_user_id', $storeUserId)->column('store_id');
            // 过滤已绑定的门店
            $model = $model->whereNotIn('id', $bindStoreIds);
        }
        $sheet = [];
        //标题 目前写在前端了
        $sheet['store_list'] = $model->gs($this->company_id)->field('id,name,address')->select()->each(function ($item){
            $storeUser = $item->storeUsers()->field('real_name,mobile')->find();
            $item->real_name  = $storeUser->real_name;
            $item->mobile     = $storeUser->mobile;
        });
        return $this->success('下载成功', $sheet);
    }

    /**
     * 模版导入
     */
    public function import(){
        $data = request()->post('sheet',[]);
        $storeUserId = request()->param('store_user_id',0);
        $errorList        = []; // 存放字段错误信息
        $failedImports    = []; // 记录导入失败数据
        $failedImportsNum = 0; // 记录导入失败的数量
        foreach ($data as $item){
           // 判断门店是否存在
            $store = Store::find($item['id']);
            if(!$store){
                $errorList[] = ['id'=>'门店不存在'];
                $failedImports[] = $item;
                $failedImportsNum++;
                continue;
            }
            // 判断门店是否已绑定
            $storeUser = StoreSalesman::where('store_id',$item['id'])->where('store_user_id',$storeUserId)->find();
            if(!$storeUser) StoreSalesman::create(['store_id'=>$item['id'],'store_user_id'=>$storeUserId]);
        }
        if($failedImportsNum > 0){
            $errorMsg    = "出现" . $failedImportsNum . "条数据导入失败，请下载错误数据并修改重新导入";
            $errorDetail = compact('errorMsg', 'errorList', 'failedImports');
            return $this->error('部分导入失败', $errorDetail);
        }
        return $this->success('导入成功',compact('errorList','failedImports','failedImportsNum'));
    }
}